package com.kung.qvs.ui.main.fragment;

import android.app.Application;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;

import com.kung.qvs.BR;
import com.kung.qvs.R;
import com.kung.qvs.data.JtRepository;
import com.kung.qvs.entity.BaseResultBean;
import com.kung.qvs.entity.KRecordWeight;
import com.kung.qvs.entity.WorkerBean;
import com.kung.qvs.entity.database.SqlManager;
import com.kung.qvs.ui.main.fragment.manage.FragWorkersItem;
import com.kung.qvs.ui.main.fragment.manage.FragWorkersModel;

import java.text.SimpleDateFormat;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class WorkloadStatisticsModel extends BaseViewModel<JtRepository> {
    public WorkloadStatisticsModel(@NonNull Application application, JtRepository model) {
        super(application, model);
    }

    public ObservableField<String> mStartDate = new ObservableField<>();
    public ObservableField<String> mEndDate = new ObservableField<>();
    //合计
    public ObservableField<String> mWeight = new ObservableField<>("0.00");    //总重量
    public ObservableField<String> mCount = new ObservableField<>("0");    //称重次数
    public ObservableField<String> mAmount = new ObservableField<>("0");    //收集数量

    //工号
    public ObservableField<String> mWorkerNo = new ObservableField<>();

    //给RecyclerView添加ObservableList
    public ObservableList<WorkloadStatisticsItem> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<WorkloadStatisticsItem> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_statistics_record);

    public ObservableField<Integer> pageSizes = new ObservableField<>(100);
    public ObservableField<Integer> pageIndex = new ObservableField<>(1);

    public ObservableField<Integer> visibleNoRecord = new ObservableField<>(View.VISIBLE);
    public WorkerBean mWorkerBean;
    //员工姓名
    public ObservableField<String> mWorkerName = new ObservableField<>();

    SimpleDateFormat kjdf2 = new SimpleDateFormat("yyyy-MM-dd");  //设置日期格式

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();
    public class UIChangeObservable {
        public SingleLiveEvent eventToSettings = new SingleLiveEvent<>();
        public SingleLiveEvent<String> eventChangeTrashType = new SingleLiveEvent<>();
        public SingleLiveEvent<KRecordWeight> eventPrintItem = new SingleLiveEvent<>();
        public SingleLiveEvent eventStartSync = new SingleLiveEvent();

        public SingleLiveEvent eventDateStart = new SingleLiveEvent();
        public SingleLiveEvent eventDateEnd = new SingleLiveEvent();
    }


    public BindingCommand onCommandDateStart = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.eventDateStart.call();
        }
    });

    public BindingCommand onCommandDateEnd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.eventDateEnd.call();
        }
    });

    //查询
    public BindingCommand onSyncTrashData = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            pageIndex.set(1);
            doGetUploadWeightBeans();
        }
    });

    //返回
    public BindingCommand onSettings = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.eventToSettings.call();
        }
    });

    @Override
    public void onCreate() {
        super.onCreate();
        //获取当前日期
        mStartDate.set(kjdf2.format(new java.util.Date()));
        mEndDate.set(kjdf2.format(new java.util.Date()));
    }

    public void funLoadWorkers() {
        model.reqSynchronizePackers("", model.getEquipmentNo(), "3", "").compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
//                        showDialog("正在请求数据...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResultBean<List<WorkerBean>>>() {
                    @Override
                    public void onNext(BaseResultBean<List<WorkerBean>> response) {
                        //请求成功
                        if (response.isSuccess()) {
                            //数据插入本地，并根据id排序查询。已被无网络情况使用
                            SqlManager.deleteWorkerBeans();
                            for(WorkerBean bean : response.entity) {
                                SqlManager.insertOrReplaceWorkerBean(bean);
                            }
                        } else {
                            //code错误时也可以定义Observable回调到View层去处理
                            ToastUtils.showShort("同步失败");
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        //关闭对话框
//                        dismissDialog();
                        if (throwable instanceof ResponseThrowable) {
                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
                            //token失效，重新登录
//                            finish();
                            //如果无网络，使用本地缓存垃圾分类
                        }
                    }

                    @Override
                    public void onComplete() {
                        //关闭对话框
                        dismissDialog();
                    }
                });
    }

    public void doGetUploadWeightBeans() {
//        String workerId = "";
//        if (mWorkerBean != null) {
//            workerId = mWorkerBean.getUserName();
//        } else {
//            ToastUtils.showShort("请刷工卡");
//            return;
//        }

        if (StringUtils.isTrimEmpty(mWorkerNo.get())) {
            ToastUtils.showShort("请刷工卡");
            observableList.clear();
            mWeight.set("0.00");
            mCount.set("0");
            mAmount.set("0");
            mWorkerName.set("");
            return;
        } else {
            mWorkerBean = SqlManager.queryProductWorkerBeanByUserName(mWorkerNo.get());
            if (mWorkerBean == null) {
                ToastUtils.showShort("工号不存在");
                observableList.clear();
                mWeight.set("0.00");
                mCount.set("0");
                mAmount.set("0");
                mWorkerName.set("");
                return;
            } else {
                mWorkerName.set(mWorkerBean.getNickName());
            }
        }

        String beginDate;
        String endDate;
        String type;
        if (StringUtils.isTrimEmpty(mStartDate.get())) {
            beginDate = "";
            endDate = "";
        } else {
            beginDate = mStartDate.get() + " 00:00:00";
            endDate = mStartDate.get() + " 23:59:59";
        }

//        if (StringUtils.isTrimEmpty(mEndDate.get())) {
//            endDate = "";
//        } else {
//            endDate = mEndDate.get() + " 23:59:59";
//        }


        //清除列表
//        if (pageIndex.get() == 1) {
            observableList.clear();
            mWeight.set("0.00");
            mCount.set("0");
            mAmount.set("0");
//        }

        model.reqGetWeightRecord("", model.getEquipmentNo(), mWorkerNo.get(), beginDate, endDate, pageSizes.get(), pageIndex.get()).compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
//                        showDialog("正在请求数据...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResultBean<List<KRecordWeight>>>() {
                    @Override
                    public void onNext(BaseResultBean<List<KRecordWeight>> response) {
                        //请求成功
                        if (response.isSuccess()) {
                            //数据插入本地，并根据id排序查询。已被无网络情况使用
                            if (response.entity == null || response.entity.size() < 1) {
                                visibleNoRecord.set(View.VISIBLE);
                                ToastUtils.showShort("没有数据");
                                return;
                            }
                            visibleNoRecord.set(View.GONE);
//                            pageIndex.set(pageIndex.get() + 1);
                            double totalWeight = mWeight.get() == null ? 0.0 : Double.parseDouble(mWeight.get());
                            int totalAmount = mAmount.get() == null ? 0 : Integer.parseInt(mAmount.get());
                            int index = 0;
                            for (KRecordWeight bean : response.entity) {
                                bean.setIndex((index + 1) + "");
                                index++;
                                observableList.add(new WorkloadStatisticsItem(WorkloadStatisticsModel.this, bean));
                                totalWeight = totalWeight + Double.parseDouble(bean.getWeight());
                                totalAmount = totalAmount + Integer.parseInt(bean.getAmount());
                            }
                            mWeight.set(String.format("%.2f", totalWeight));
                            mCount.set(observableList.size() + "");
                            mAmount.set(totalAmount + "");
                        } else {
                            //code错误时也可以定义Observable回调到View层去处理
//                            ToastUtils.showShort(response.getErrorMsg());
                            visibleNoRecord.set(View.VISIBLE);
                            ToastUtils.showShort("没有数据");
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        //关闭对话框
//                        dismissDialog();
                        if (throwable instanceof java.util.concurrent.TimeoutException) {

                        } else if (throwable instanceof ResponseThrowable) {
                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
                            //token失效，重新登录
//                            finish();
                            //如果无网络，使用本地缓存垃圾分类
                        }
                    }

                    @Override
                    public void onComplete() {
                        //关闭对话框
//                        dismissDialog();
                    }
                });
    }

    public void doGetWorkerByCode() {
        pageIndex.set(1);
        if (StringUtils.isTrimEmpty(mWorkerNo.get())) {
            ToastUtils.showShort("请刷工卡");
            observableList.clear();
            mWeight.set("0.00");
            mCount.set("0");
            mAmount.set("0");
            mWorkerName.set("");
            return;
        }
        mWorkerBean = SqlManager.queryProductWorkerBeanByUserName(mWorkerNo.get());
        if (mWorkerBean == null) {
            ToastUtils.showShort("工号不存在");
            observableList.clear();
            mWeight.set("0.00");
            mCount.set("0");
            mAmount.set("0");
            mWorkerName.set("");
            return;
        }
        mWorkerName.set(mWorkerBean.getNickName());
        doGetUploadWeightBeans();
    }
}
